<template>
  <div class="flash-sale-container">
    <el-card class="flash-sale-banner">
      <div class="banner-content">
        <div class="banner-left">
          <h1 class="banner-title">限时秒杀</h1>
          <p class="banner-desc">每日精选商品，限量抢购</p>
        </div>
        <div class="banner-right">
          <div class="countdown-container">
            <div class="countdown-title">
              <span v-if="timePeriods.length && timePeriods[currentPeriodIndex]?.status === 'active'">距离本场结束还剩</span>
              <span
                v-else-if="timePeriods.length && timePeriods[currentPeriodIndex]?.status === 'upcoming'">距离开始还剩</span>
              <span v-else>距离明日场次开始还剩</span>
            </div>
            <div class="countdown">
              <div class="time-block">
                <span class="time">{{ countdown.hours }}</span>
                <span class="unit">时</span>
              </div>
              <div class="time-block">
                <span class="time">{{ countdown.minutes }}</span>
                <span class="unit">分</span>
              </div>
              <div class="time-block">
                <span class="time">{{ countdown.seconds }}</span>
                <span class="unit">秒</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 秒杀时间段选择 -->
    <div class="time-periods">
      <div v-for="(period, index) in timePeriods" :key="index" class="time-period-item"
        :class="{ active: currentPeriodIndex === index, 'status-active': period.status === 'active', 'status-upcoming': period.status === 'upcoming', 'status-finished': period.status === 'finished' }"
        @click="selectTimePeriod(index)">
        <div class="period-name">{{ period.name }}</div>
        <div class="period-time">{{ period.time }}</div>
        <div class="period-status" :class="period.status">{{ getPeriodStatus(period) }}</div>
      </div>
      <!-- 功能按钮组 -->
      <div class="action-buttons-group">
        <el-button v-if="isAdmin" type="primary" @click="dialogVisible = true" class="add-product-btn">
          <el-icon><Plus /></el-icon>添加商品
        </el-button>
        <el-button type="success" @click="showPurchaseRecords = true" class="records-btn">
          <el-icon><Document /></el-icon>我的记录
        </el-button>
        <el-button type="info" @click="refreshStock" :loading="refreshingStock" class="refresh-btn">
          <el-icon><Refresh /></el-icon>刷新库存
        </el-button>
      </div>
    </div>

    <!-- 添加商品模态框 -->
    <el-dialog v-model="dialogVisible" title="添加秒杀商品" width="650px">
      <el-form :model="productForm" :rules="rules" ref="productFormRef" label-width="100px">
        <!-- 添加显示当前选择的秒杀场次信息 -->
        <el-form-item label="秒杀场次">
          <el-tag v-if="timePeriods.length && currentPeriodIndex >= 0"
            :type="getTagType(timePeriods[currentPeriodIndex].status)">
            {{ timePeriods[currentPeriodIndex].name }} {{ timePeriods[currentPeriodIndex].time }}
            ({{ getPeriodStatus(timePeriods[currentPeriodIndex]) }})
          </el-tag>
          <el-tag v-else type="info">未选择场次</el-tag>
        </el-form-item>

        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="productForm.productName" placeholder="请输入商品名称"></el-input>
        </el-form-item>

        <el-form-item label="原价" prop="originalPrice">
          <el-input-number v-model="productForm.originalPrice" :precision="2" :step="10" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="秒杀价" prop="flashPrice">
          <el-input-number v-model="productForm.flashPrice" :precision="2" :step="10" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="productForm.stock" :min="0" :step="1"></el-input-number>
        </el-form-item>

        <el-form-item label="商品主图" prop="mainImage">
          <el-input v-model="productForm.mainImage" placeholder="请输入商品主图链接">
            <template #append>
              <el-button @click="previewMainImage">预览</el-button>
            </template>
          </el-input>
          <div v-if="productForm.mainImage" class="image-preview">
            <img :src="productForm.mainImage" class="preview-image" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 秒杀商品列表 -->
    <div class="flash-sale-products" v-loading="loading">
      <el-empty v-if="flashSaleProducts.length === 0" description="暂无秒杀商品" />
      <el-row :gutter="20" v-else>
        <el-col :xs="12" :sm="12" :md="8" :lg="6" v-for="product in flashSaleProducts" :key="product.id">
          <div class="flash-sale-product-card">
            <div class="product-image">
              <img :src="product.mainImage" :alt="product.name">
              <div class="discount-badge">{{ (product.flashPrice / product.originalPrice * 10).toFixed(1) }}折</div>
              <!-- 添加删除和修改按钮 -->
              <div class="action-buttons">
                <el-button type="danger" circle size="small" class="delete-btn"
                  @click.stop="handleDeleteProduct(product)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </el-button>
                <el-button type="primary" circle size="small" class="edit-btn" @click.stop="handleEditProduct(product)">
                  <el-icon>
                    <Edit />
                  </el-icon>
                </el-button>
              </div>
            </div>
            <div class="product-info">
              <h3 class="product-name">{{ product.name }}</h3>
              <div class="product-price">
                <span class="current-price">¥{{ product.flashPrice }}</span>
                <span class="original-price">¥{{ product.originalPrice }}</span>
              </div>
              <div class="progress-container">
                <div class="progress-text">
                  <span>已抢{{ calculateSoldPercent(product) }}%</span>
                  <span class="stock-info" :class="{ 'low-stock': product.stock <= 10, 'out-of-stock': product.stock <= 0 }">
                    <el-icon><Box /></el-icon>
                    剩余{{ product.stock }}件
                  </span>
                </div>
                <el-progress
                  :percentage="calculateSoldPercent(product)"
                  :stroke-width="8"
                  :color="getProgressColor(product.stock)"
                  :show-text="false"
                />
                <div class="real-time-indicator" v-if="product.isUpdating">
                  <el-icon class="rotating"><Loading /></el-icon>
                  <span>实时更新中...</span>
                </div>
              </div>
              <el-button type="danger" size="large" class="buy-now-btn"
                :disabled="!isCurrentPeriodActive || product.stock <= 0" @click="handleBuyNow(product)">
                {{ getBuyButtonText(product) }}
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 秒杀规则说明 -->
    <el-card class="flash-sale-rules">
      <template #header>
        <div class="card-header">
          <h3>秒杀规则</h3>
        </div>
      </template>
      <div class="rules-content">
        <p><strong>1. 活动时间：</strong>每日10:00、14:00、20:00准时开始，每场持续2小时</p>
        <p><strong>2. 参与条件：</strong>所有用户均可参与，无需预约</p>
        <p><strong>3. 购买限制：</strong>每个用户每件秒杀商品限购1件</p>
        <p><strong>4. 支付时间：</strong>下单后请在15分钟内完成支付，否则订单自动取消</p>
        <p><strong>5. 发货说明：</strong>秒杀商品将在3个工作日内发货</p>
        <p><strong>6. 售后服务：</strong>秒杀商品支持7天无理由退货（质量问题除外）</p>
      </div>
    </el-card>

    <!-- 添加修改商品模态框 -->
    <el-dialog v-model="editDialogVisible" title="修改秒杀商品" width="650px">
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
        <!-- 添加显示当前选择的秒杀场次信息 -->
        <el-form-item label="秒杀场次">
          <el-tag v-if="timePeriods.length && currentPeriodIndex >= 0"
            :type="getTagType(timePeriods[currentPeriodIndex].status)">
            {{ timePeriods[currentPeriodIndex].name }} {{ timePeriods[currentPeriodIndex].time }}
            ({{ getPeriodStatus(timePeriods[currentPeriodIndex]) }})
          </el-tag>
          <el-tag v-else type="info">未选择场次</el-tag>
        </el-form-item>

        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="editForm.productName" placeholder="请输入商品名称"></el-input>
        </el-form-item>

        <el-form-item label="商品ID">
          <el-input v-model="editForm.id" disabled></el-input>
        </el-form-item>

        <el-form-item label="原价" prop="originalPrice">
          <el-input-number v-model="editForm.originalPrice" :precision="2" :step="10" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="秒杀价" prop="flashPrice">
          <el-input-number v-model="editForm.flashPrice" :precision="2" :step="10" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="editForm.stock" :min="0" :step="1"></el-input-number>
        </el-form-item>

        <el-form-item label="商品主图" prop="mainImage">
          <el-input v-model="editForm.mainImage" placeholder="请输入商品主图链接">
            <template #append>
              <el-button @click="previewEditImage">预览</el-button>
            </template>
          </el-input>
          <div v-if="editForm.mainImage" class="image-preview">
            <img :src="editForm.mainImage" class="preview-image" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 购买记录对话框 -->
    <el-dialog v-model="showPurchaseRecords" title="我的秒杀记录" width="80%" :before-close="closePurchaseRecords">
      <div class="purchase-records-container">
        <div class="records-header">
          <el-date-picker
            v-model="recordsDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="fetchPurchaseRecords"
            class="date-picker"
          />
          <el-button type="primary" @click="fetchPurchaseRecords" :loading="loadingRecords">
            <el-icon><Search /></el-icon>查询
          </el-button>
        </div>

        <el-table :data="purchaseRecords" v-loading="loadingRecords" stripe>
          <el-table-column prop="createTime" label="购买时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="商品名称" min-width="200" />
          <el-table-column prop="flashPrice" label="秒杀价格" width="120">
            <template #default="scope">
              <span class="price">¥{{ scope.row.flashPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="originalPrice" label="原价" width="120">
            <template #default="scope">
              <span class="original-price">¥{{ scope.row.originalPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getOrderStatusType(scope.row.status)">
                {{ getOrderStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="总金额" width="120">
            <template #default="scope">
              <span class="total-amount">¥{{ scope.row.totalAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button
                v-if="scope.row.status === 0"
                type="primary"
                size="small"
                @click="payOrder(scope.row)"
              >
                去支付
              </el-button>
              <el-button
                v-else-if="scope.row.status === 2"
                type="info"
                size="small"
                disabled
              >
                已取消
              </el-button>
              <el-button
                v-else
                type="success"
                size="small"
                disabled
              >
                已完成
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="records-pagination" v-if="recordsTotal > 0">
          <el-pagination
            v-model:current-page="recordsPage"
            v-model:page-size="recordsPageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="recordsTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="fetchPurchaseRecords"
            @current-change="fetchPurchaseRecords"
          />
        </div>

        <el-empty v-if="purchaseRecords.length === 0 && !loadingRecords" description="暂无购买记录" />
      </div>
    </el-dialog>

    <!-- 用户引导组件 -->
    <UserGuide type="flash-sale" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { Delete, Edit, Plus, Box, Loading, Document, Refresh, Search } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import UserGuide from '@/components/UserGuide.vue'

const router = useRouter()
const loading = ref(false)
const flashSaleProducts = ref([])
const currentFlashSale = ref(null)

// 实时库存更新相关
const refreshingStock = ref(false)

// 购买记录相关
const showPurchaseRecords = ref(false)
const purchaseRecords = ref([])
const loadingRecords = ref(false)
const recordsDateRange = ref([])
const recordsPage = ref(1)
const recordsPageSize = ref(10)
const recordsTotal = ref(0)

// 倒计时数据
const countdown = ref({
  hours: '00',
  minutes: '00',
  seconds: '00'
})

// 秒杀时间段
const timePeriods = ref([])
const currentPeriodIndex = ref(0)

// 判断当前选中的时间段是否进行中
const isCurrentPeriodActive = computed(() => {
  return timePeriods.value.length && timePeriods.value[currentPeriodIndex.value]?.status === 'active'
})

// 选择时间段
const selectTimePeriod = (index) => {
  currentPeriodIndex.value = index
  fetchFlashSaleProducts()
}

// 获取时间段状态文本
const getPeriodStatus = (period) => {
  if (period.status === 'finished') return '已结束'
  if (period.status === 'active') return '抢购中'
  return '即将开始'
}

// 根据时间段状态获取标签类型
const getTagType = (status) => {
  if (status === 'finished') return 'info'
  if (status === 'active') return 'success'
  return 'warning'
}

// 获取购买按钮文本
const getBuyButtonText = (product) => {
  if (!isCurrentPeriodActive.value) {
    if (!timePeriods.value.length) return '未开始'
    return timePeriods.value[currentPeriodIndex.value]?.status === 'finished' ? '已结束' : '未开始'
  }
  if (product.stock <= 0) {
    return '已抢光'
  }
  return '立即抢购'
}

// 处理立即购买
const handleBuyNow = async (product) => {
  if (!isCurrentPeriodActive.value || product.stock <= 0) {
    return
  }

  // 检查用户是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录后再参与秒杀')
    router.push('/login')
    return
  }

  try {
    // 调用秒杀接口
    const userId = localStorage.getItem('userId') || '1' // 获取用户ID，默认为1
    const res = await request.post('/flash-sale/purchase', {
      flashSaleId: timePeriods.value[currentPeriodIndex.value].id,
      productId: product.id,
      userId: userId,
      quantity: 1
    })

    if (res && res.code === 200) {
      ElMessage.success(res.message || '秒杀成功')

      // 添加到购物车并跳转到结算页面
      const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]')

      // 检查商品是否已在购物车中
      const existingItem = cartItems.find(item => item.id === product.id)

      if (existingItem) {
        ElMessage.warning('该秒杀商品已在购物车中')
      } else {
        // 如果不存在，添加新商品
        cartItems.push({
          id: product.id,
          name: product.name,
          price: product.flashPrice, // 使用秒杀价格
          mainImage: product.mainImage,
          quantity: 1,
          isFlashSale: true // 标记为秒杀商品
        })

        // 保存回localStorage
        localStorage.setItem('cartItems', JSON.stringify(cartItems))

        // 触发购物车更新事件
        window.emitter?.emit('cart-updated')

        router.push('/home/cart')
      }
    } else {
      ElMessage.error(res.message || '秒杀失败，请稍后再试')
    }
  } catch (error) {
    console.error('秒杀请求失败:', error)
    ElMessage.error('秒杀失败，请稍后再试')
  }
}

// 更新时间段状态
const updatePeriodStatus = async () => {
  try {
    // 创建固定的三个时间段
    const now = new Date();
    console.log('当前时间:', now);
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

    // 定义三个固定时间段
    const periods = [
      {
        id: 1,
        name: '上午场',
        startHour: 10,
        endHour: 12,
        time: '10:00',
      },
      {
        id: 2,
        name: '下午场',
        startHour: 14,
        endHour: 16,
        time: '14:00',
      },
      {
        id: 3,
        name: '晚间场',
        startHour: 20,
        endHour: 22,
        time: '20:00',
      }
    ];

    // 处理时间段状态
    timePeriods.value = periods.map(period => {
      const startTime = new Date(today);
      startTime.setHours(period.startHour, 0, 0, 0);

      const endTime = new Date(today);
      endTime.setHours(period.endHour, 0, 0, 0);

      let status = 'upcoming'; // 默认为即将开始

      // 如果当前时间在开始和结束时间之间，则为活动中
      if (now >= startTime && now < endTime) {
        status = 'active';
      }
      // 如果当前时间已经超过了结束时间，则为已结束
      else if (now >= endTime) {
        status = 'finished';

        // 如果已经结束，设置为明天的时间段
        startTime.setDate(startTime.getDate() + 1);
        endTime.setDate(endTime.getDate() + 1);
      }

      console.log(`${period.name} 状态:`, status, '开始时间:', startTime, '结束时间:', endTime);

      return {
        id: period.id,
        name: period.name,
        time: period.time,
        startHour: period.startHour,
        endHour: period.endHour,
        status: status,
        startTime: startTime,
        endTime: endTime
      };
    });

    // 自动选择当前或最近的时间段
    let activeIndex = timePeriods.value.findIndex(p => p.status === 'active');
    if (activeIndex >= 0) {
      // 如果有活动中的时间段，选择它
      currentPeriodIndex.value = activeIndex;
      console.log('选择活动中的时间段:', timePeriods.value[activeIndex].name);
    } else {
      // 否则找到最近的即将开始的时间段
      const upcomingIndex = timePeriods.value.findIndex(p => p.status === 'upcoming');
      if (upcomingIndex >= 0) {
        currentPeriodIndex.value = upcomingIndex;
        console.log('选择即将开始的时间段:', timePeriods.value[upcomingIndex].name);
      } else {
        // 如果所有时间段都已结束，选择第一个（明天的）
        currentPeriodIndex.value = 0;
        console.log('所有时间段已结束，选择第一个时间段:', timePeriods.value[0].name);
      }
    }

    // 获取选中时间段的秒杀商品
    fetchFlashSaleProducts();
  } catch (error) {
    console.error('获取秒杀时间段失败:', error);
    ElMessage.error('获取秒杀时间段失败');
  }
}

// 更新倒计时
let countdownTimer = null
const updateCountdown = () => {
  // 获取当前时间
  const now = new Date();
  let endTime = new Date();

  // 根据当前选中的时间段确定结束时间
  if (!timePeriods.value.length || currentPeriodIndex.value < 0) {
    // 默认设置为24小时后
    endTime.setHours(endTime.getHours() + 24);
  } else {
    const currentPeriod = timePeriods.value[currentPeriodIndex.value];

    if (currentPeriod.status === 'active') {
      // 如果当前时间段是活动中，倒计时到结束时间
      endTime = new Date(currentPeriod.endTime);
      console.log('活动中，倒计时到结束时间:', endTime);
    } else if (currentPeriod.status === 'upcoming') {
      // 如果当前时间段是即将开始，倒计时到开始时间
      endTime = new Date(currentPeriod.startTime);
      console.log('即将开始，倒计时到开始时间:', endTime);
    } else {
      // 如果当前时间段已结束，倒计时到明天的开始时间
      endTime = new Date(currentPeriod.startTime); // 使用已经设置好的明天的开始时间
      console.log('已结束，倒计时到明天的开始时间:', endTime);
    }
  }

  const timeLeft = endTime - now;
  console.log('倒计时剩余毫秒数:', timeLeft);

  // 计算剩余时间
  let hours = Math.floor(timeLeft / (1000 * 60 * 60));
  let minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
  let seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

  // 格式化时间
  countdown.value = {
    hours: hours.toString().padStart(2, '0'),
    minutes: minutes.toString().padStart(2, '0'),
    seconds: seconds.toString().padStart(2, '0')
  };

  console.log('倒计时:', countdown.value);
}

// 获取秒杀商品
const fetchFlashSaleProducts = async () => {
  if (!timePeriods.value.length || currentPeriodIndex.value < 0) {
    return;
  }

  const currentPeriod = timePeriods.value[currentPeriodIndex.value];
  if (!currentPeriod || !currentPeriod.id) {
    return;
  }

  loading.value = true;
  try {
    // 调用后端API获取秒杀商品
    const res = await request.get(`/flash-sale/products/${currentPeriod.id}`);
    console.log('获取秒杀商品响应:', res);

    if (res && res.data) {
      // 处理返回的商品数据，只显示状态为1（上架）的商品
      flashSaleProducts.value = res.data
        .filter(product => product.status === 1)
        .map(product => {
          // 计算售出百分比
          const total = product.stock + product.soldCount;
          const soldPercent = total > 0 ? Math.floor((product.soldCount * 100) / total) : 0;

          return {
            id: product.id,
            name: product.productName,
            originalPrice: product.originalPrice,
            flashPrice: product.flashPrice,
            discountPercent: product.discountPercent,
            mainImage: product.mainImage || 'https://element-plus.org/images/element-plus-logo.svg', // 默认图片
            stock: product.stock,
            soldCount: product.soldCount,
            soldPercent: soldPercent,
            status: product.status
          };
        });
    } else {
      flashSaleProducts.value = [];
      console.log('没有获取到秒杀商品数据或数据格式不正确');
    }
  } catch (error) {
    console.error('获取秒杀商品失败:', error);
    ElMessage.error('获取秒杀商品失败');
    flashSaleProducts.value = [];
  } finally {
    loading.value = false;
  }
}

// 判断是否为管理员
const isAdmin = computed(() => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  return userInfo.role === 'admin'
})

// 添加商品相关
const dialogVisible = ref(false)
const productFormRef = ref(null)
const productForm = reactive({
  productName: '',
  originalPrice: 0,
  flashPrice: 0,
  stock: 0,
  mainImage: '',
})

// 表单验证规则
const rules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  originalPrice: [
    { required: true, message: '请输入原价', trigger: 'blur' }
  ],
  flashPrice: [
    { required: true, message: '请输入秒杀价', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存', trigger: 'blur' }
  ],
  mainImage: [
    { required: true, message: '请输入商品主图链接', trigger: 'blur' }
  ]
}

// 预览主图
const previewMainImage = () => {
  if (!productForm.mainImage) {
    ElMessage.warning('请先输入图片链接')
    return
  }
  const img = new Image()
  img.onload = () => {
    ElMessage.success('图片链接有效')
  }
  img.onerror = () => {
    ElMessage.error('图片链接无效，请检查链接是否正确')
  }
  img.src = productForm.mainImage
}

// 提交表单
const submitForm = async () => {
  if (!productFormRef.value) return

  // 先检查是否选择了秒杀场次
  if (!timePeriods.value.length || currentPeriodIndex.value < 0) {
    ElMessage.error('请先选择秒杀场次')
    return
  }

  const currentPeriod = timePeriods.value[currentPeriodIndex.value]
  if (!currentPeriod || !currentPeriod.id) {
    ElMessage.error('无法获取当前秒杀场次信息')
    return
  }

  await productFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 计算折扣百分比 (秒杀价 / 原价 * 10)，保留一位小数
        const discountPercent = Math.round((productForm.flashPrice / productForm.originalPrice) * 100)

        const productData = {
          flashSaleId: currentPeriod.id,
          productName: productForm.productName,
          mainImage: productForm.mainImage,
          originalPrice: productForm.originalPrice,
          flashPrice: productForm.flashPrice,
          discountPercent: discountPercent,
          stock: productForm.stock,
          soldCount: 0,
          limitPerUser: 1,
          status: 1
        }

        const res = await request.post('/flash-sale/admin/product/add', productData)

        if (res.code === 200) {
          ElMessage.success('添加秒杀商品成功')
          dialogVisible.value = false
          resetForm()
          fetchFlashSaleProducts() // 刷新商品列表
        } else {
          ElMessage.error(res.message || '添加秒杀商品失败')
        }
      } catch (error) {
        console.error('添加秒杀商品失败:', error)
        ElMessage.error('添加秒杀商品失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (productFormRef.value) {
    productFormRef.value.resetFields()
  }
  productForm.mainImage = ''
}

// 处理删除商品
const handleDeleteProduct = async (product) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个秒杀商品吗？删除后将无法恢复。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用删除接口，真正删除商品
    const res = await request.delete(`/flash-sale/admin/product/delete/${product.id}`)

    if (res.code === 200) {
      ElMessage.success('商品已成功删除')
      fetchFlashSaleProducts() // 刷新商品列表
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('下架秒杀商品失败:', error)
      ElMessage.error('下架失败')
    }
  }
}

// 修改商品相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  id: null,
  productName: '',
  originalPrice: 0,
  flashPrice: 0,
  stock: 0,
  mainImage: '',
})

// 处理修改商品
const handleEditProduct = (product) => {
  editForm.id = product.id
  editForm.productName = product.name
  editForm.originalPrice = product.originalPrice
  editForm.flashPrice = product.flashPrice
  editForm.stock = product.stock
  editForm.mainImage = product.mainImage
  editDialogVisible.value = true
}

// 预览修改的主图
const previewEditImage = () => {
  if (!editForm.mainImage) {
    ElMessage.warning('请先输入图片链接')
    return
  }
  const img = new Image()
  img.onload = () => {
    ElMessage.success('图片链接有效')
  }
  img.onerror = () => {
    ElMessage.error('图片链接无效，请检查链接是否正确')
  }
  img.src = editForm.mainImage
}

// 提交修改表单
const submitEditForm = async () => {
  if (!editFormRef.value) return

  // 先检查是否选择了秒杀场次
  if (!timePeriods.value.length || currentPeriodIndex.value < 0) {
    ElMessage.error('请先选择秒杀场次')
    return
  }

  const currentPeriod = timePeriods.value[currentPeriodIndex.value]
  if (!currentPeriod || !currentPeriod.id) {
    ElMessage.error('无法获取当前秒杀场次信息')
    return
  }

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 计算折扣百分比 (秒杀价 / 原价 * 10)，保留一位小数
        const discountPercent = Math.round((editForm.flashPrice / editForm.originalPrice) * 100)

        const productData = {
          id: editForm.id,
          flashSaleId: currentPeriod.id,
          productName: editForm.productName,
          mainImage: editForm.mainImage,
          originalPrice: editForm.originalPrice,
          flashPrice: editForm.flashPrice,
          discountPercent: discountPercent,
          stock: editForm.stock,
          limitPerUser: 1,
          status: 1
        }

        const res = await request.put('/flash-sale/admin/product/update', productData)

        if (res.code === 200) {
          ElMessage.success('修改秒杀商品成功')
          editDialogVisible.value = false
          fetchFlashSaleProducts() // 刷新商品列表
        } else {
          ElMessage.error(res.message || '修改秒杀商品失败')
        }
      } catch (error) {
        console.error('修改秒杀商品失败:', error)
        ElMessage.error('修改秒杀商品失败')
      }
    }
  })
}

onMounted(() => {
  // 初始化时间段状态
  updatePeriodStatus()

  // 初始化倒计时
  updateCountdown()

  // 设置定时器，每秒更新倒计时
  countdownTimer = setInterval(() => {
    updateCountdown()

    // 每分钟更新一次时间段状态
    if (new Date().getSeconds() === 0) {
      updatePeriodStatus()
    }
  }, 1000)
})

// 计算售出百分比
const calculateSoldPercent = (product) => {
  const total = product.stock + product.soldCount
  return total > 0 ? Math.floor((product.soldCount * 100) / total) : 0
}

// 获取进度条颜色
const getProgressColor = (stock) => {
  if (stock <= 0) return '#F56C6C'
  if (stock <= 10) return '#E6A23C'
  return '#67C23A'
}

// 刷新库存
const refreshStock = async () => {
  if (!timePeriods.value.length || currentPeriodIndex.value < 0) {
    return
  }

  refreshingStock.value = true
  try {
    const currentPeriod = timePeriods.value[currentPeriodIndex.value]

    // 为每个商品获取实时库存
    for (let product of flashSaleProducts.value) {
      product.isUpdating = true
      try {
        const res = await request.get(`/flash-sale/stock/${currentPeriod.id}/${product.id}`)
        if (res && res.data) {
          product.stock = res.data.stock
        }
      } catch (error) {
        console.error(`获取商品${product.id}库存失败:`, error)
      } finally {
        product.isUpdating = false
      }
    }

    ElMessage.success('库存刷新成功')
  } catch (error) {
    console.error('刷新库存失败:', error)
    ElMessage.error('刷新库存失败')
  } finally {
    refreshingStock.value = false
  }
}

// 获取购买记录
const fetchPurchaseRecords = async () => {
  loadingRecords.value = true
  try {
    const userId = localStorage.getItem('userId') || '1'
    const params = {
      userId,
      page: recordsPage.value,
      pageSize: recordsPageSize.value
    }

    if (recordsDateRange.value && recordsDateRange.value.length === 2) {
      params.startDate = recordsDateRange.value[0]
      params.endDate = recordsDateRange.value[1]
    }

    const res = await request.get('/flash-sale/user/records', { params })
    if (res && res.data) {
      purchaseRecords.value = res.data.records || []
      recordsTotal.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取购买记录失败:', error)
    ElMessage.error('获取购买记录失败')
  } finally {
    loadingRecords.value = false
  }
}

// 关闭购买记录对话框
const closePurchaseRecords = () => {
  showPurchaseRecords.value = false
  purchaseRecords.value = []
  recordsDateRange.value = []
  recordsPage.value = 1
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  switch (status) {
    case 0: return 'warning'  // 待支付
    case 1: return 'success'  // 已支付
    case 2: return 'danger'   // 已取消
    case 3: return 'info'     // 已退款
    default: return 'info'
  }
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  switch (status) {
    case 0: return '待支付'
    case 1: return '已支付'
    case 2: return '已取消'
    case 3: return '已退款'
    default: return '未知'
  }
}

// 支付订单
const payOrder = (order) => {
  ElMessage.info('跳转到支付页面...')
  // 这里可以跳转到支付页面
  router.push(`/payment/${order.orderNo}`)
}

onUnmounted(() => {
  // 清除定时器
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<style scoped>
.flash-sale-container {
  padding: 20px;
}

.flash-sale-banner {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #FF4949 0%, #FF7E7E 100%);
  color: white;
}

.banner-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.banner-title {
  font-size: 28px;
  font-weight: bold;
  margin: 0 0 10px 0;
}

.banner-desc {
  font-size: 16px;
  margin: 0;
}

.countdown-container {
  text-align: center;
}

.countdown-title {
  font-size: 14px;
  margin-bottom: 10px;
}

.countdown {
  display: flex;
  gap: 8px;
}

.time-block {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.time {
  background-color: rgba(0, 0, 0, 0.3);
  color: white;
  font-size: 24px;
  font-weight: bold;
  padding: 5px 10px;
  border-radius: 4px;
  min-width: 40px;
  text-align: center;
}

.unit {
  font-size: 12px;
  margin-top: 5px;
}

.time-periods {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  overflow-x: auto;
  padding-bottom: 10px;
}

.time-period-item {
  min-width: 80px;
  padding: 15px;
  text-align: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.time-period-item.active {
  background-color: #FF4949;
  color: white;
}

.time-period-item.active .period-name,
.time-period-item.active .period-status {
  color: rgba(255, 255, 255, 0.8);
}

.period-name {
  font-size: 14px;
  margin-bottom: 3px;
  color: #606266;
}

.period-time {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.period-status {
  font-size: 12px;
  font-weight: bold;
  padding: 2px 6px;
  border-radius: 10px;
  display: inline-block;
}

/* 为不同状态的时间段添加不同的样式 */
.time-period-item:not(.active) .period-status {
  background-color: rgba(0, 0, 0, 0.05);
}

.time-period-item.status-active {
  border: 1px solid #67C23A;
}

.time-period-item.status-upcoming {
  border: 1px solid #E6A23C;
}

.time-period-item.status-finished {
  border: 1px solid #909399;
  opacity: 0.8;
}

.period-status.active {
  color: #67C23A;
}

.period-status.upcoming {
  color: #E6A23C;
}

.period-status.finished {
  color: #909399;
}

.flash-sale-products {
  margin-bottom: 30px;
  min-height: 300px;
}

.flash-sale-product-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  transition: all 0.3s;
}

.flash-sale-product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.2);
}

.product-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.discount-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #FF4949;
  color: white;
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: bold;
}

.product-info {
  padding: 15px;
}

.product-name {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
}

.current-price {
  font-size: 20px;
  font-weight: bold;
  color: #FF4949;
}

.original-price {
  font-size: 14px;
  color: #909399;
  text-decoration: line-through;
}

.progress-container {
  margin-bottom: 15px;
}

.progress-text {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #606266;
  margin-bottom: 5px;
}

.buy-now-btn {
  width: 100%;
}

.flash-sale-rules {
  margin-bottom: 20px;
}

.rules-content {
  font-size: 14px;
  line-height: 1.8;
  color: #606266;
}

.rules-content p {
  margin: 10px 0;
}

/* 深色模式适配 */
html.dark .time-period-item {
  background-color: #1d1e1f;
}

html.dark .flash-sale-product-card {
  background-color: #1d1e1f;
}

html.dark .rules-content {
  color: #e5eaf3;
}

.action-buttons {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 2;
  display: flex;
  gap: 8px;
}

.delete-btn,
.edit-btn {
  opacity: 0.8;
  transition: opacity 0.3s;
}

.delete-btn:hover,
.edit-btn:hover {
  opacity: 1;
}

.edit-btn {
  background-color: #409EFF;
  border-color: #409EFF;
  color: white;
}

.edit-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.preview-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.image-preview {
  margin-top: 10px;
  margin-bottom: 10px;
}

.action-buttons-group {
  display: flex;
  gap: 10px;
  margin-left: auto;
  align-items: center;
}

.add-product-btn, .records-btn, .refresh-btn {
  display: flex;
  align-items: center;
}

.add-product-btn .el-icon,
.records-btn .el-icon,
.refresh-btn .el-icon {
  margin-right: 5px;
}

/* 库存相关样式 */
.stock-info {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stock-info.low-stock {
  color: #E6A23C;
}

.stock-info.out-of-stock {
  color: #F56C6C;
}

.real-time-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 购买记录对话框样式 */
.purchase-records-container {
  max-height: 600px;
}

.records-header {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.date-picker {
  flex: 1;
  max-width: 300px;
}

.records-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.price {
  color: #F56C6C;
  font-weight: bold;
}

.original-price {
  color: #909399;
  text-decoration: line-through;
}

.total-amount {
  color: #67C23A;
  font-weight: bold;
}
</style>
